package com.luoxue.mito.controller;

import com.luoxue.mito.config.MitoConfig;
import com.luoxue.mito.dao.MitoPostRepository;
import com.luoxue.mito.entity.MitoPost;
import com.luoxue.mito.util.GsonUtil;
import com.luoxue.mito.util.MitoUtil;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.rest.webmvc.RepositoryRestController;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RepositoryRestController
public class MitoPostController {
    private static final String baseUrl = "/mitoPosts";


    @Resource
    private MitoPostRepository repository;

    @Resource
    private MitoConfig mitoConfig;

    @RequestMapping(value = baseUrl + "/{id}", method = RequestMethod.GET)
    public ResponseEntity<?> getInfo(@PathVariable Long id) {
        MitoPost item = repository.getById(id);
        String fileBaseUrl = mitoConfig.getFileBaseUrl();
        if (Strings.isNotBlank(item.getServerPic())) {
            item.setPic(fileBaseUrl + item.getServerPic());
        }
        if (Strings.isNotBlank(item.getServerImages())) {
            List<String> serverImageList = GsonUtil.GsonToList(item.getServerImages(), String.class);
            item.setImages(GsonUtil.GsonString(serverImageList.stream().map(serverImage -> fileBaseUrl + serverImage).collect(Collectors.toList())));
        }
        item.setServerPic(null);
        item.setServerImages(null);
        MitoPost mitoPost = new MitoPost();
        BeanUtils.copyProperties(item, mitoPost);
        return ResponseEntity.ok(mitoPost);
    }

    @RequestMapping(value = baseUrl + "/list", method = RequestMethod.GET)
    public ResponseEntity<?> list(MitoPost mitoPost) {
        if (mitoPost.getSortField() != null && "hot".equals(mitoPost.getSortField())) {
            mitoPost.setSortField("pageViews");
        } else {
            mitoPost.setSortField("dataFlag");
        }
        if (Strings.isNotBlank(mitoPost.getTags())) {
            mitoPost.setTags(String.format("\"%s\"", mitoPost.getTags()));
        }

        Specification<MitoPost> specification = (root, criteriaQuery, criteriaBuilder) -> {
            // 查询条件的集合
            List<Predicate> list = new ArrayList<>();
            if (Strings.isNotBlank(mitoPost.getTitle())) {
                list.add(criteriaBuilder.or(
                        criteriaBuilder.like(root.get("title"), MitoUtil.likeContact(mitoPost.getTitle())),
                        criteriaBuilder.like(root.get("summary"), MitoUtil.likeContact(mitoPost.getTitle()))));
            }
            if (Strings.isNotBlank(mitoPost.getCategory())) {
                list.add(criteriaBuilder.equal(root.get("category"), mitoPost.getCategory()));
            }
            if (Strings.isNotBlank(mitoPost.getTags())) {
                list.add(criteriaBuilder.like(root.get("tags"), MitoUtil.likeContact(mitoPost.getTags())));
            }
            // 转数组
            Predicate[] predicates = new Predicate[list.size()];
            list.toArray(predicates);
            return criteriaBuilder.and(predicates);
        };
        Page<MitoPost> page = MitoUtil.findAll(repository, mitoPost, specification, Sort.by(Sort.Order.desc(mitoPost.getSortField()), Sort.Order.desc("id")));

        String fileBaseUrl = mitoConfig.getFileBaseUrl();
        page.getContent().forEach(item -> {
            if (Strings.isNotBlank(item.getServerPic())) {
                item.setPic(fileBaseUrl + item.getServerPic());
            }
            item.setImages(null);
            item.setServerPic(null);
            item.setServerImages(null);
            item.setTags(null);
        });
        return ResponseEntity.ok(page);
    }
}
